package what.the.fun.dao;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import what.the.fun.domain.AnswerStatistic;
import what.the.fun.domain.Survey;
import what.the.fun.jdbc.AnswerStatisticRowMapper;
import what.the.fun.jdbc.SurveyRowMapper;

public class SurveyDAOImpl implements SurveyDAO{

	@Autowired
	DataSource dataSource;
	JdbcTemplate jdbcTemplate;
	String sql;
	
	@Override
	public List<Survey> getDataList() {
		sql = "call sp_survey_GetAll ()";
		jdbcTemplate = new JdbcTemplate(dataSource);
		
		List<Survey> list = new ArrayList<Survey>();
		list = jdbcTemplate.query(sql, new SurveyRowMapper());
		
		return list;
	}

	@Override
	public void insertData(Survey survey) {
		sql = "call sp_survey_Insert (?, ?)";
		jdbcTemplate = new JdbcTemplate(dataSource);
		
		jdbcTemplate.update(sql, survey.getName(), survey.getCampId());
	}

	@Override
	public void updateData(Survey survey) {
		sql = "call sp_survey_Update (?, ?, ?)";
		jdbcTemplate = new JdbcTemplate(dataSource);
		
		jdbcTemplate.update(sql, survey.getName(), survey.getCampId(), survey.getSurveyId());
	}

	@Override
	public void deleteData(String id) {
		sql = "call sp_survey_Delete (?)";
		jdbcTemplate = new JdbcTemplate(dataSource);
		
		jdbcTemplate.update(sql, id);
	}

	@Override
	public Survey getData(String id) {
		sql = "call sp_survey_GetById (?)";
		jdbcTemplate = new JdbcTemplate(dataSource);
		
		List<Survey> list = new ArrayList<Survey>();
		list = jdbcTemplate.query(sql, new SurveyRowMapper(), id);
		
		return list.get(0);
	}

	@Override
	public List<Survey> getSurveyListByCampId(String campId) {
		sql = "call sp_survey_GetSurveyListByCampId (?)";
		jdbcTemplate = new JdbcTemplate(dataSource);
		
		List<Survey> list = new ArrayList<Survey>();
		list = jdbcTemplate.query(sql, new SurveyRowMapper(), campId);
		
		return list;
	}

	@Override
	public List<AnswerStatistic> getAnswerStatisticListBySurveyId(String id) {
		sql = "call sp_result_GetAnswerStatisticListBySurveyId (?)";
		jdbcTemplate = new JdbcTemplate(dataSource);
		
		List<AnswerStatistic> list = new ArrayList<AnswerStatistic>();
		list = jdbcTemplate.query(sql, new AnswerStatisticRowMapper(), id);
		
		return list;
	}

}
